package com.scaffold.springbootscaffold.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component
public class WebSocketChannelInterceptor implements ChannelInterceptor {

    @Resource
    private WebSocketSessionManager sessionManager;

    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        if (accessor == null) {
            return message;
        }

        String sessionId = accessor.getSessionId();
        StompCommand command = accessor.getCommand();

        // 连接时
        if (StompCommand.CONNECT.equals(command)) {
            String userId = accessor.getFirstNativeHeader("userId");
            if (userId != null) {
                sessionManager.addSession(userId, sessionId);
            }
        }
        // 断开时
        else if (StompCommand.DISCONNECT.equals(command)) {
            sessionManager.removeSession(sessionId);
        }

        return message;
    }
} 